/*
 * @Author: gk 
 * @Date: 2018-08-03 12:36:45 
 * @Last Modified by: gk
 * @Last Modified time: 2018-04-24 14:22:54
 * 打印控件
 */
layui.define(['zlConfig', 'layer'], function (exports) {
    "use strict";
    var $ = layui.$
        , layer = layui.layer
        , device = layui.device()
        , zlConfig = layui.zlConfig
        , MOD_NAME = 'zlPrint'
        , CLASS_NAME = '.layui-dropdown-menu'
        //事件类型，默认为'mouseover'（移动端则为'click'）
        , event = (device.android || device.ios) ? 'click' : 'mouseover';
    //组件重画消息处理
    layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.WM_DRAW, null, function (WParam) {
        if (WParam && $(WParam.elem).attr('class') && $(WParam.elem).attr('class').indexOf('zlprint') >= 0) {
            //自动完成渲染
            obj.render($(WParam.elem), WParam.value);
        }
    });

    //隐藏
    var __hideDropdown = function (e) {
        if (isClosable(e.target)
            && isClosable(e.target.parentElement)
            && isClosable(e.target.parentElement.parentElement)) {
            obj.hide();
        }
    };

    //判断dropdown是否可以隐藏
    var isClosable = function (elem) {
        return elem
            && elem.className.indexOf('layui-btn-dropdown') == -1
            && elem.className.indexOf('layui-dropdown-menu') == -1;
    };

    var obj = {
        paramsCallBacks: {},
        //修正显示位置
        hide: function () {
            if (this && this.inst && this.inst.is(':visible')) {
                this.inst.css('display', 'none');
                $('body').off(event, __hideDropdown);
            }
        },
        /**
         * url打开新的窗口
         * url 路径
         * params 参数
         */
        iframePost: function (url, params) {
            var temp_form = document.createElement("form");
            temp_form.action = url;
            temp_form.target = "_blank";
            temp_form.method = "post";
            temp_form.style.display = "none";
            for (var x in params) {
                var opt = document.createElement("textarea");
                opt.name = x;
                opt.value = params[x];
                temp_form.appendChild(opt);
            }
            document.body.appendChild(temp_form);
            temp_form.submit();
            document.body.removeChild(temp_form);
        },
        //渲染
        render: function () {
            var $elem = $('.zlprint');
            //数据获取
            //初始化dom
            $(".zlprint").each(function (index, item) {
                var replist = eval('(' + $(item).attr('replist') + ')');
                obj.init($(item), replist);
            })
        },
        init: function ($elem, replist, datas) {
            var that = this;
            if (!$elem.hasClass('layui-btn-dropdown')) {
                $elem.addClass("layui-btn-dropdown");
                var btnHtml = ['<button type="button" class="layui-btn layui-btn-sm" data-toggle="dropdown">'
                    , '    <img src="' + layui.cache['contentPath'] + '/static/appdata/filesres/ico/A846AFC1D63E457F9BFAD447FDFDC5D4.png" style="width:16px;height:16px;">'
                    , '    <span>打印</span>'
                    , '    <span class="layui-icon" style="font-size: 14px"></span>'
                    , '</button>'];
                var items = []
                var ids = {};
                $.each(replist, function (index, item) {
                    ids[item.id] = item;
                    items = items.concat([
                        , '	<li>'
                        , '	    <a href="#" id="' + item.id + '">'
                        , '	    <img src="' + item.ico + '" style="width:16px;height:16px;">' + item.title + '</a>'
                        , '	</li>'
                    ]);
                });
                var menuHtml = ['<ul class="layui-dropdown-menu">'
                    , items.join('')
                    , '</ul>'];
                $elem.append(btnHtml.join(''));
                $elem.append(menuHtml.join(''));
                for (var id in ids) {
                    $('#' + id).click(function () {
                        var btnId=this.id;
                        var params = {};
                        if (obj.paramsCallBacks[btnId]) {
                            params = obj.paramsCallBacks[btnId]();
                        }
                        obj.iframePost(ids[btnId].url, params);
                    });
                };
            }
            $('.layui-btn-dropdown').each(function (index, elem) {
                var reElem = $(elem);
                reElem.data('id', 'dropdown-' + index);
                event = (device.android || device.ios) ? 'click' : 'mouseover';

                reElem[event](function () {
                    if (!that.inst//第一次显示
                        || that.currReElem.data('id') != reElem.data('id')//切换到其他dropdown
                        || (that.currReElem.data('id') == reElem.data('id') && !that.inst.is(':visible'))) {//重新移动到当前dropdown
                        //隐藏
                        that.hide();
                        //这里暂时采用fixed定位
                        var dropElem = reElem.find(CLASS_NAME),
                            left = reElem.offset().left - $(window).scrollLeft(),
                            top = reElem.offset().top + reElem.height() - $(window).scrollTop() - 2,
                            containerWidth = reElem.width(),
                            dropWidth = dropElem.width(),
                            offsetRight = left + containerWidth,
                            overflow = (left + dropWidth) > $(window).width(),
                            css = { 'display': 'block', 'position': 'fixed', 'top': top + 'px', 'left': left + 'px' };

                        overflow && $.extend(true, css, { 'left': (offsetRight - dropWidth) + 'px' });
                        //显示
                        dropElem.css(css).on('click', 'li', function () {
                            dropElem.css('display', 'none');
                        });

                        that.inst = dropElem;
                        that.currReElem = reElem;
                        $('body').on(event, __hideDropdown);
                    }
                });
            });
        },
        regeditparamCallBack: function (id, callback) {
            obj.paramsCallBacks[id] = callback;
        }
    };
    $(window).scroll(function () {
        obj.hide();
    });
    obj.render();
    exports(MOD_NAME, obj);
});
//**打印时候调用函数 */
function onPrint(url) {
    var toUrl = url;
    window.open(url);
};